﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Event.Annotations;

namespace Event
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
        }
        GuShi KJGU = new GuShi();
        GuShi GNGU = new GuShi();
        private void Form1_Load(object sender, EventArgs e)
        {
            new TaskFactory().StartNew(() =>
            {
                while (true)
                {
                    KJGU.Price = new Random().Next(0, 100);
                    Thread.Sleep(1000);
                    GNGU.Price = new Random().Next(0, 100);
                    Thread.Sleep(1000);
                }
            });
        }
        Person PX = new Person() { Name = "小白" };
        Person PD = new Person() { Name = "大白" };
        private void button1_Click(object sender, EventArgs e)
        {
            KJGU.PriceChanged += PX.DoThing;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            KJGU.PriceChanged -= PX.DoThing;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            GNGU.PriceChanged += PD.DoThing;

        }

        private void button4_Click(object sender, EventArgs e)
        {
            GNGU.PriceChanged -= PD.DoThing;
        }
    }

    public class GuShi
    {
        private int _price;
        public int Price { get => _price; set => Set(ref _price, value); }
        public event Action<int> PriceChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPriceChanged(string propertyName)
        {
            PriceChanged?.Invoke(Price);
        }

        private void Set<T>(ref T val, T newval, [CallerMemberName] string name = "")
        {
            if (!EqualityComparer<T>.Default.Equals(val, newval))
            {
                val = newval;
                OnPriceChanged(name);
            }
        }
    }

    public class Person
    {
        public string Name { get; set; }

        public void DoThing(int price)
        {
            Console.WriteLine($"【{Name}】收到了价格【{price}】");
        }
    }
}
